package app

import (
	"fmt"
	"net/http"
	"strings"

	//. "gitee.com/tomatomeatman/golang-repository/bricks/utils/function/app"
	. "gitee.com/tomatomeatman/golang-repository/bricks/utils/function/data"

	. "gitee.com/tomatomeatman/golang-repository/bricks/model"
	. "gitee.com/tomatomeatman/golang-repository/bricks/utils/gin"

	//. "gitee.com/tomatomeatman/golang-repository/bricks/utils/gorm"
	"github.com/gin-gonic/gin"
)

type BrickApp struct{}

/**
 * 程序运行
 * @param InterceptorFunc 拦截函数
 */
func (this BrickApp) Run(InterceptorFunc func(ctx *gin.Context) bool) {
	Root := AppUtil{}.ReadConfigKey("System", "Root", "/webroot/").(string)
	Port := AppUtil{}.ReadConfigKey("System", "Port", "8080").(string)
	Title := AppUtil{}.ReadConfigKey("System", "Title", "").(string)
	Name := AppUtil{}.ReadConfigKey("System", "Name", "").(string)
	GinMode := AppUtil{}.ReadConfigKey("System", "Gin", "Release").(string)

	//DbNamedRules = AppUtil{}.ReadConfigKey("DataSource", "DbNamedRules", "common").(string) //common 通用数据库命名格式定义;bricks 自定义的格式

	go Cloud{}.RegistraCloud() //注册服务到注册中心

	HttpHandleInfos := GinUtil{}.GetController()

	switch strings.ToUpper(GinMode) { //gin运行模式
	case "RELEASE":
		gin.SetMode(gin.ReleaseMode)
		break
	case "TEST":
		gin.SetMode(gin.TestMode)
		break
	case "DEBUG":
		gin.SetMode(gin.DebugMode)
		break
	default:
		gin.SetMode(gin.ReleaseMode)
	}

	r := gin.Default()

	GinUtil{}.SetCors(r)             //设置跨域
	GinUtil{}.SetStatic(r, "."+Root) //设置静态目录

	for key, val := range HttpHandleInfos {
		switch val.Type {
		case GET:
			r.GET(key, GinUtil{}.GetHandleFunc(key, InterceptorFunc, HttpHandleInfos))
			break
		case POST:
			r.POST(key, GinUtil{}.GetHandleFunc(key, InterceptorFunc, HttpHandleInfos))
			break
		case DELETE:
			r.DELETE(key, GinUtil{}.GetHandleFunc(key, InterceptorFunc, HttpHandleInfos))
			break
		case PUT:
			r.PUT(key, GinUtil{}.GetHandleFunc(key, InterceptorFunc, HttpHandleInfos))
			break
		case OPTIONS:
			r.OPTIONS(key, GinUtil{}.GetHandleFunc(key, InterceptorFunc, HttpHandleInfos))
			break
		default:
			r.GET(key, func(ctx *gin.Context) {
				ctx.JSONP(http.StatusBadRequest, MsgEmity{}.Err(1001, "请求方式错误,不支持此方式"))
			})
		}
	}

	fmt.Println(StringUtil{}.Append("================ ", Title, Name, "启动完毕,使用端口:", Port, " ================"))

	r.Run(":" + Port) // 监听并在 0.0.0.0:8080 上启动服务
}
